/*
 * @Author: your name
 * @Date: 2021-01-06 11:38:26
 * @LastEditTime: 2021-05-18 21:27:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \express-seed\routes\updataImg.JS
 */
const express = require("express");
const router = express.Router();
const Result = require("../../models/result.js");
const upload = require("../../utils/multer.js");
const { selectImgService, addImgService, delImgService } = require("../../service/imgService");
//获取图片列表
router.get("/", async (req, res, next) => {
    const { status, results } = await selectImgService();
    if (status) {
        new Result(results, "查询成功").success(res);
    } else {
        new Result({}, "查询失败").fail(res);
    }
});
//添加图片
router.post("/add_img", upload.array("photos"), async (req, res, next) => {
    console.log("req.files :>> ", req.files);
    console.log(" req.body :>> ", req.body);
    let imgsInfo = []; //图片信息数组
    req.files.forEach((file) => {
        let obj = {};
        obj.name = file.filename;
        obj.imgPath = `public/img/${obj.name}`;
        obj.path = file.path;
        imgsInfo.push(obj);
    });
    const { status, results } = await addImgService(imgsInfo);
    if (status) {
        const data = {
            imgsInfo,
            count: imgsInfo.length,
            results,
        };
        new Result(data, "上传成功").success(res);
    } else {
        new Result({}, "上传失败").fail(res);
    }
    // fs.unlinkSync('./uploads/' + filename); 调用fs模块的unlinkSync方法，传入文件路径，直接删除。也可以用fs.unlink(callback)这个异步删除。
    /*  const ress = await addImgService()
     new Result(ress, '添加成功').success(res) */
});

//根据id删除图片
router.post("/delete_img", async (req, res, next) => {
    const { img_id } = req.body;
    const ress = await delImgService(img_id);
    if (ress) {
        new Result({ img_id }, "删除成功").success(res);
    } else {
        new Result({}, "删除失败").fail(res);
    }
});

module.exports = router;
